package com.siwei.mes.controller;

import cn.dev33.satoken.stp.SaLoginConfig;
import cn.dev33.satoken.stp.SaLoginModel;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.siwei.mes.common.annotation.AnonymousAccess;
import com.siwei.mes.common.result.Json;
import com.siwei.mes.common.util.MapUtils;
import com.siwei.mes.entity.User;
import com.siwei.mes.entity.dto.LoginDto;
import com.siwei.mes.entity.vo.LoginVo;
import com.siwei.mes.mapper.UserMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Map;

import static com.siwei.mes.common.exception.handler.MessageHandler.assertTrue;

/**
 * @Description: 登录授权
 * @Version: 1.0
 * @author: chenmaolin
 * @date: 2023/11/21 18:59
 */
@Slf4j
@RestController
@Api(tags = "登录授权接口")
@RequestMapping("auth")
public class AuthController {
    @Resource
    private UserMapper userMapper;

    @ApiOperation("登录接口")
    @PostMapping("login")
    @AnonymousAccess
    public Json login(@RequestBody @Valid LoginVo loginVo) {
        String userPhone = loginVo.getUserPhone();
        String password = loginVo.getPassword();
        String device = loginVo.getDevice().trim().toUpperCase();

        /**判断用户信息是否存在*/
        User user = userMapper.selectByUserPhone(userPhone);
        assertTrue(user == null, "用户不存在!");
        user = userMapper.selectByPhoneAndPassword(userPhone, password);
        assertTrue(user == null, "用户名密码错误!");

        LoginDto loginDto = new LoginDto().setUserId(user.getId()).setUserName(user.getUserName())
                .setUserPhone(user.getUserPhone()).setAvatar(user.getAvatar()).setJob(user.getJob()).setRoleId(user.getRoleId()).setRoleName(user.getRoleName());

        Map<String, Object> userMap = MapUtils.beanToMap(loginDto);
        SaLoginModel saLoginModel = SaLoginConfig.setExtraData(userMap);
        saLoginModel.setDevice(device);

        StpUtil.login(user.getId(), saLoginModel);

        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        loginDto.setTokenName(tokenInfo.getTokenName());
        loginDto.setTokenValue(tokenInfo.getTokenValue());

        /**把试验项目权限加进来*/
        loginDto.setTestProjectJson(user.getTestProjectJson());
        return Json.succ().data(loginDto);
    }
}
